<template>
  <div
    v-loading="loading || getGoodListLoading"
    class="good-list-wrapper"
    element-loading-text="加载中..."
  >
    <div class="good-list">
      <div class="title">
        <div class="line"></div>
        <h4 class="text">产品列表</h4>
      </div>
      <div class="line"></div>

      <div class="body">
        <div class="sidebar">
          <div class="header">
            <h4>产品分类</h4>
            <el-space :size="0" :spacer="spacer">
              <HLink v-permission="'goods_addType'" @click="onAddGoodType">新增分类</HLink>
              <HLink v-if="!editshow" v-permission="'goods_editType'" @click="editshow = !editshow">
                点击编辑
              </HLink>
              <HLink v-else @click="editshow = !editshow">点击完成</HLink>
            </el-space>
          </div>
          <div class="line"></div>
          <div class="trees_container" style="width: 220px">
            <div
              :class="{ tree_item: true, active_tree_item: !activeTypeId }"
              @click="handleGoodTypeSelect({ id: 0, name: '' }, { level: 0 })"
            >
              {{ goodTypeList[0].name }}</div
            >
            <div class="tree_box">
              <el-tree
                :accordion="true"
                class="tree"
                style="max-width: 100%"
                :data="goodTypeList[0].childData"
                :props="goodTypeTreeProps"
                node-key="id"
                @node-click="handleGoodTypeSelect"
              >
                <template #default="{ node, data }">
                  <span
                    class="custom-tree-node"
                    :class="{
                      is_active_tree_item: activeTypeId == data.id,
                      is_disable: data.disabled,
                    }"
                  >
                    <span style="height: 100%">
                      <ShowTooltip
                        placement="top"
                        :ref-name="'testName' + node.id"
                        class-name="is_textClass"
                        :content="node.label"
                        :is-text="true"
                        :color="activeTypeId == data.id ? '#fff' : data.disabled ? '#999' : '#666'"
                        :size="12"
                        :offset="5"
                        :show-after="300"
                      ></ShowTooltip>
                    </span>
                    <div
                      v-if="editshow"
                      style="
                        position: absolute;
                        right: 0;
                        display: flex;
                        gap: 8px;
                        z-index: 999;
                        padding-right: 2px;
                      "
                    >
                      <el-icon size="14" @click.stop="onEditGoodType(node, data)">
                        <EditPen />
                      </el-icon>
                      <el-icon size="14" @click.stop="onDelGoodType(node, data)">
                        <Delete />
                      </el-icon>
                    </div>
                  </span>
                </template>
              </el-tree>
            </div>
          </div>
        </div>
        <div class="line"></div>
        <div class="main">
          <div class="header">
            <div class="btn_group">
              <HPlainButton v-permission="'goods_add'" @click="addProduct"> 新增 </HPlainButton>
              <HPlainButton v-permission="'goods_import'" @click="onImportGoods('in')">
                导入
              </HPlainButton>
              <h-plain-button v-permission="'goods_bomImport'" @click="onBomImportClick">
                BOM导入
              </h-plain-button>
              <HPlainButton v-permission="'goods_export'" @click="onImportGoods('out')">
                导出
              </HPlainButton>
              <el-dropdown trigger="click">
                <HButton :disabled="selectedGoods.length == 0">
                  批量操作
                  <el-icon class="el-icon--right">
                    <arrow-down />
                  </el-icon>
                </HButton>
                <template #dropdown>
                  <el-dropdown-menu>
                    <div v-permission="'goods_enabled'">
                      <el-dropdown-item @click="handleMultipleOperate('enable')">
                        批量启用
                      </el-dropdown-item>
                    </div>
                    <div v-permission="'goods_disabled'">
                      <el-dropdown-item @click="handleMultipleOperate('disable')">
                        批量禁用
                      </el-dropdown-item>
                    </div>
                    <div v-permission="'goods_delete'">
                      <el-dropdown-item @click="handleMultipleOperate('delete')">
                        批量删除
                      </el-dropdown-item>
                    </div>
                    <div v-permission="'goods_serviceModality'">
                      <el-dropdown-item @click="serviceModalityConnectModalVisible = true">
                        关联服务形式
                      </el-dropdown-item>
                    </div>
                    <div v-permission="'goods_enabledNo'">
                      <el-dropdown-item @click="handleMultipleEnableOrDisableBatchNo(true)">
                        启用批号管理
                      </el-dropdown-item>
                    </div>
                    <div v-permission="'goods_disabledNo'">
                      <el-dropdown-item @click="handleMultipleEnableOrDisableBatchNo(false)">
                        禁用批号管理
                      </el-dropdown-item>
                    </div>
                    <div v-permission="'goods_disabledNo'">
                      <el-dropdown-item @click="handleUpdateMobileVisibleClick(1)">
                        移动端显示
                      </el-dropdown-item>
                    </div>
                    <div v-permission="'goods_disabledNo'">
                      <el-dropdown-item @click="handleUpdateMobileVisibleClick(0)">
                        移动端隐藏
                      </el-dropdown-item>
                    </div>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <div class="search">
              <el-select
                v-model="getGoodListParam.goodsType"
                placeholder="请选择类型"
                clearable
                @change="getList"
              >
                <el-option :value="1" label="成品" />
                <el-option :value="2" label="物料" />
              </el-select>
              <el-select
                v-model="getGoodListParam.brandId"
                placeholder="请选择品牌"
                clearable
                :loading="getBrandOptionsLoading"
                @change="getList"
              >
                <template #header>
                  <div class="select_header">
                    <el-input
                      v-model.trim="getBrandOptionsKeyword"
                      @keyup.enter="getBrandOptions"
                    />
                    <h-plain-button @click="getBrandOptions">搜索</h-plain-button>
                  </div>
                </template>
                <el-option
                  v-for="item in brandOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
              <el-select
                v-model="getGoodListParam.source"
                placeholder="请选择来源"
                clearable
                @change="getList"
              >
                <el-option :value="1" label="系统创建" />
                <el-option :value="2" label="excel导入" />
                <el-option :value="3" label="金蝶ERP" />
                <el-option :value="4" label="第三方接口创建" />
              </el-select>

              <!-- 请选择单位 -->
              <el-select
                v-model="getGoodListParam.unitId"
                placeholder="请选择单位"
                clearable
                :loading="getUnitOptionsLoading"
                @change="getList"
              >
                <template #header>
                  <div class="select_header">
                    <el-input v-model.trim="getUnitOptionsKeyword" @keyup.enter="getUnitOptions" />
                    <h-plain-button @click="getUnitOptions">搜索</h-plain-button>
                  </div>
                </template>
                <el-option
                  v-for="item in unitOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
              <el-input
                v-model.trim="getGoodListParam.keyword"
                placeholder="请输入物料名称/编号/型号/规格"
                clearable
                @keyup.enter="getList"
                @clear="getList"
              />
              <HButton type="primary" @click="getList">
                <el-icon>
                  <Search />
                </el-icon>
                搜索
              </HButton>
              <HButton @click="onReset">
                <el-icon>
                  <RefreshRight />
                </el-icon>
                重置
              </HButton>
            </div>
          </div>
          <div class="table-pagination-wrapper">
            <div class="table">
              <el-table
                ref="tableInstance"
                :border="true"
                stripe
                resizable
                :data="goodList"
                height="100%"
                @selection-change="handleGoodSelect"
                @row-dblclick="onGoToGoodDetail"
              >
                <el-table-column type="selection" width="40" fixed />

                <!-- 序号 -->
                <el-table-column
                  show-overflow-tooltip
                  type="index"
                  label="序号"
                  width="50"
                  fixed
                  :align="'center'"
                />

                <!-- 编号 -->
                <el-table-column show-overflow-tooltip prop="code" label="编号" min-width="150">
                  <template #default="scope">
                    <h-link @click="onGoToGoodDetail(scope.row)">
                      {{ scope.row.code }}
                    </h-link>
                  </template>
                </el-table-column>

                <!-- 编号 -->
                <!-- <el-table-column
                  show-overflow-tooltip
                  prop="saleModels"
                  label="销售型号"
                  width="150"
                /> -->

                <!-- 名称 -->
                <el-table-column show-overflow-tooltip prop="name" label="名称" width="240" />

                <!-- 所属部门 -->
                <!-- <el-table-column show-overflow-tooltip label="所属部门" width="120">
                  <template #default="{ row }">
                    <template v-if="row.department">
                      {{ row.department.map((item) => item.name).join('、') }}
                    </template>
                  </template>
                </el-table-column> -->

                <!-- 质保周期 -->
                <!-- <el-table-column
                  show-overflow-tooltip
                  prop="warrantyDay"
                  label="质保周期"
                  width="80"
                /> -->

                <!-- 规格 -->
                <el-table-column show-overflow-tooltip prop="specName" label="规格" width="240" />

                <!-- 类型 -->
                <!--<el-table-column show-overflow-tooltip prop="name" label="类型" width="74">-->
                <!--  <template #default="scope">-->
                <!--    {{ scope.row.goodsType === 1 ? '成品' : '物料' }}-->
                <!--  </template>-->
                <!--</el-table-column>-->

                <!-- 品牌 -->
                <!-- <el-table-column show-overflow-tooltip prop="brand" label="品牌" width="90" /> -->

                <!-- 型号 -->
                <!-- <el-table-column show-overflow-tooltip prop="model" label="型号" width="220" /> -->

                <!-- 分类 -->
                <el-table-column show-overflow-tooltip label="分类" width="140">
                  <template #default="i">
                    {{ [i.row.type, i.row.typeTwo, i.row.typeThree].filter((o) => o).join('-') }}
                  </template>
                </el-table-column>

                <!-- 单位 -->
                <el-table-column show-overflow-tooltip prop="unit" label="单位" width="50" />

                <!-- 来源 -->
                <el-table-column show-overflow-tooltip prop="source" label="来源" width="140">
                  <template #default> SAP </template>
                </el-table-column>

                <!-- 是否为核心件 -->
                <!-- <el-table-column label="是否为核心件" width="140">
                  <template #header>
                    <el-dropdown trigger="click">
                      <div style="display: flex; align-items: center">
                        <span
                          :style="{
                            color: getGoodListParam.coreMaterials === null ? '' : '#007cff',
                          }"
                        >
                          是否为核心件
                        </span>
                        <el-icon class="el-icon--right">
                          <arrow-down />
                        </el-icon>
                      </div>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="handleCoreMaterialFilter(true)"
                            >是</el-dropdown-item
                          >
                          <el-dropdown-item @click="handleCoreMaterialFilter(false)"
                            >否</el-dropdown-item
                          >
                          <el-dropdown-item @click="handleCoreMaterialFilter(null)"
                            >重置</el-dropdown-item
                          >
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </template>
                  <template #default="{ row }">
                    {{ row.coreMaterials ? '是' : '否' }}
                  </template>
                </el-table-column> -->

                <!-- 批号管理 -->
                <!-- <el-table-column label="批号管理" width="80">
                  <template #default="{ row }">
                    {{ row.enableBatchNo ? '启用' : '禁用' }}
                  </template>
                </el-table-column> -->

                <!-- 单价 -->
                <el-table-column label="单价" width="140" prop="price">
                  <template #default="{ row }"> ￥{{ row.price.toFixed(2) }} </template>
                </el-table-column>

                <el-table-column label="移动端状态" width="100">
                  <template #default="{ row }">
                    {{ row.mobileVisible === 1 ? '显示' : '隐藏' }}
                  </template>
                </el-table-column>

                <!-- 单价2 -->
                <!-- <el-table-column label="单价2" width="100" prop="overPrice">
                  <template #default="{ row }"> ￥{{ row.overPrice.toFixed(2) }} </template>
                </el-table-column> -->

                <!-- 创建时间 -->
                <el-table-column
                  show-overflow-tooltip
                  prop="createTime"
                  label="创建时间"
                  width="128"
                />

                <!-- 更新时间 -->
                <el-table-column
                  show-overflow-tooltip
                  prop="updateTime"
                  label="更新时间"
                  width="128"
                />

                <!-- 状态 -->
                <el-table-column
                  prop="status"
                  label="状态"
                  width="70"
                  fixed="right"
                  :align="'center'"
                >
                  <template #default="scope">
                    <HStatus v-if="!scope.row.status">启用</HStatus>
                    <HStatus v-else type="info">禁用</HStatus>
                  </template>
                </el-table-column>

                <el-table-column label="操作" width="70" fixed="right" :align="'center'">
                  <template #default="{ row }">
                    <h-link @click="handleEditClick(row)">修改</h-link>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <div class="pagination">
              <span>已选中&nbsp;{{ selectedGoods.length }}&nbsp;条</span>
              <Pagination
                ref="paginationInstance"
                :list_total="goodListTotal"
                @size-change="getList"
                @current-change="getList"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <AddCommodityType
      v-model:visible="addCommodityTypeDialogVisible"
      type="commodity"
      @update="getGoodsTypeFun"
    />
    <UpdateCommodityType
      v-model:visible="updateCommodityTypeDialogVisible"
      :update-type="currentEditCommodityType"
      type="commodity"
      @update="getGoodsTypeFun"
    />

    <service-modality-connect-modal
      v-model:visible="serviceModalityConnectModalVisible"
      :product-ids="goodSelectIdList"
    />
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import {
    Action,
    ElDivider,
    ElMessage,
    ElMessageBox,
    MessageBoxState,
    TableInstance,
  } from 'element-plus'
  import { Search, Delete, ArrowDown, RefreshRight, EditPen, Trophy } from '@element-plus/icons-vue'
  import { ref, onMounted, reactive, h, computed } from 'vue'
  import { useRouter } from 'vue-router'
  import {
    brandPageSelect,
    unitPageSelect,
    getGoodsType,
    setGoodListMobileVisible,
  } from '@/api/goodsInfo'
  import { multipleEnableOrDisableBatchNo, typeDelete } from '@/api/goodsSet'
  import { goodsExportExcel } from '@/api/upload'
  import moment from 'moment'
  import { GoodType } from './types'
  import { useProduct, useSpare, useGoodType } from './services'
  import { Good } from './services/types'
  import _ from 'lodash'
  import AddCommodityType from '@/components/pages/common/type/add-type/AddType.vue'
  import UpdateCommodityType from '@/components/pages/common/type/update-type/UpdateType.vue'
  import { UpdateCommodityTypeProps } from '@/components/pages/common/type/update-type/types'
  import type Node from 'element-plus/es/components/tree/src/model/node'
  import routeComponentName from '@/config/route-component-name'
  import ServiceModalityConnectModal from '@/components/pages/good/ServiceModalityConnectModal.vue'
  import { useGetGoodList } from '@/services/pages/good/useGood'
  import { HMessage, HMessageBox } from '@/components/common/message'

  const {
    goodList,
    goodListTotal,
    getGoodListParam,
    getGoodListLoading,
    getGoodList,
    resetGetGoodListParam,
  } = useGetGoodList()
  const { setGoodType } = useGoodType()
  const { productMultipleDelete, productMultipleEnable, productMultipleDisable } = useProduct()
  const { spareMultipleDelete, spareMultipleEnable, spareMultipleDisable } = useSpare()

  defineOptions({
    name: routeComponentName.good.goodList,
  })

  // 分页组件实例
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)

  // 新增分类弹窗显示状态
  const addCommodityTypeDialogVisible = ref(false)

  // 编辑分类弹窗显示状态
  const updateCommodityTypeDialogVisible = ref(false)

  // 全局路由对象
  const router = useRouter()

  // 物料选择列表（存储的是物料的id）
  const goodSelectIdList = computed(() => {
    return selectedGoods.value.map((good) => good.id)
  })

  // 服务形式关联弹窗显示状态
  const serviceModalityConnectModalVisible = ref(false)

  // 当前正在编辑的分类
  const currentEditCommodityType = ref<UpdateCommodityTypeProps>({
    id: '',
    name: '',
    parentId: '',
    status: false,
    level: 1,
  })

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  /**
   * 商品分类树形选择器配置
   */
  const goodTypeTreeProps = {
    children: 'childData',
    label: 'name',
  }

  // 商品选择列表
  const selectedGoods = ref<Array<GoodItem>>([])

  // 选中的分类id
  const activeTypeId = ref('')

  // 表格组件实例
  const tableInstance = ref<TableInstance | null>(null)

  // 商品分类列表
  const goodTypeList = ref<Array<{ id: number; name: string; childData: Array<GoodType> }>>([
    {
      id: 0,
      name: '全部',
      childData: [],
    },
  ])

  /**
   * bom导入点击时触发
   */
  const onBomImportClick = () => {
    router.push({ name: 'goodBomImport' })
  }

  /**
   * 新增分类
   */
  const onAddGoodType = () => {
    addCommodityTypeDialogVisible.value = true
  }

  /**
   * 编辑分类
   * @param {Node} node - 编辑的节点
   * @param {Object} d - 分类对象
   */
  const onEditGoodType = (node: Node, d) => {
    currentEditCommodityType.value = {
      id: d.id,
      status: d.disabled,
      name: d.name,
      parentId: node.parent.data.id || '0',
      level: d.level,
    }
    updateCommodityTypeDialogVisible.value = true
  }

  /**
   * 获取列表
   */
  const getList = () => {
    if (paginationInstance.value) {
      getGoodListParam.value.limit = paginationInstance.value.size
      getGoodListParam.value.page = paginationInstance.value.current
      getGoodList()
    }
  }

  /**
   * 重置事件
   */
  const onReset = () => {
    activeTypeId.value = ''
    resetGetGoodListParam()
    getList()
  }

  /**
   * 商品分类选择事件
   * @param {Object} d - 分类对象
   * @param {Object} n - 树形节点对象
   */
  const handleGoodTypeSelect = (d, n) => {
    if (d.disabled) return
    activeTypeId.value = d.id
    resetGetGoodListParam()
    switch (n.level) {
      case 1:
        getGoodListParam.value.typeId = d.id
        ruleForm.parentId = d.id
        break
      case 2:
        getGoodListParam.value.typeId = n.parent.data.id
        getGoodListParam.value.typeTwoId = d.id
        break
      case 3:
        getGoodListParam.value.typeId = n.parent.parent.data.id
        getGoodListParam.value.typeTwoId = n.parent.data.id
        getGoodListParam.value.typeThreeId = n.data.id
        break
      default:
        break
    }
    getList()
  }

  const onDelGoodType = (n, d) => {
    ruleForm.id = d.id
    ElMessageBox({
      type: 'error',
      title: '确认是否删除',
      message: '您确认删除该分类？',
      showCancelButton: true,
    })
      .then(() => {
        typeDelete([ruleForm.id]).then((res) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            plain: true,
            duration: 5000,
            showClose: true,
          })
          getGoodsTypeFun()
          onReset()
        })
      })
      .catch(() => {
        // 切不可删除该注释，否则会引起eslint的报错
      })
  }

  /**
   * 商品选择事件
   * @param {Array<GoodItem>} goods - 选择的商品列表
   */
  const handleGoodSelect = (goods: Array<GoodItem>) => {
    selectedGoods.value = _.cloneDeep(goods)
  }

  const editshow = ref(false)

  const loading = ref(false)

  // 表单数据
  const ruleForm = reactive({
    id: '',
    name: '',
    parentId: '',
    parentName: '',
  })

  // 搜索框下拉数据
  const brandOptions = ref([])
  const unitOptions = ref([])

  const getUnitOptionsLoading = ref(false)
  const getUnitOptionsKeyword = ref('')
  const getUnitOptions = async () => {
    getUnitOptionsLoading.value = true
    const data = {
      limit: 0,
      name: getUnitOptionsKeyword.value,
      page: 0,
    }
    const res = await unitPageSelect(data)
    unitOptions.value = res.data.data.rows
    getUnitOptionsLoading.value = false
  }

  const getBrandOptionsKeyword = ref('')
  const getBrandOptionsLoading = ref(false)
  const getBrandOptions = async () => {
    getBrandOptionsLoading.value = true
    const data = {
      limit: 0,
      name: getBrandOptionsKeyword.value,
      page: 0,
    }
    const res = await brandPageSelect(data)
    brandOptions.value = res.data.data.rows
    getBrandOptionsLoading.value = false
  }

  const onImportGoods = async (str) => {
    if (str == 'out') {
      const filter = { ...getGoodListParam.value }
      let isExportAllData = true
      filter.brandId && (isExportAllData = false)
      filter.keyword && (isExportAllData = false)
      filter.source && (isExportAllData = false)
      filter.typeId && (isExportAllData = false)
      filter.unitId && (isExportAllData = false)
      filter.goodsType && (isExportAllData = false)

      ElMessageBox({
        type: 'warning',
        message: isExportAllData
          ? '当前筛选条件为空，将导出全部物料，是否确定？'
          : '是否导出所筛选的物料？',
        showCancelButton: true,
        confirmButtonText: isExportAllData ? '确定' : '是',
        cancelButtonText: isExportAllData ? '取消' : '否',
        title: '提示',
      })
        .then(() => {
          loading.value = true
          // TODO
          goodsExportExcel(filter).then((res) => {
            loading.value = false
            ElMessage({
              type: res.data.code && !res.data.success ? 'error' : 'success',
              message:
                res.data.code && !res.data.success ? res.data.message : '物料资料数据导出成功',
              plain: true,
              duration: 5000,
              showClose: true,
            })
            if (res.data.code && !res.data.success) {
              return
            }
            const url = window.URL.createObjectURL(new Blob([res.data], { type: '.xlsx' }))
            const link = document.createElement('a')
            link.href = url
            link.download = `物料资料_${moment(new Date()).format('YYYY-MM-DD')}.xlsx`
            link.click()
          })
        })
        .catch(() => {
          // 不可以删除该注释，否则会引起报错
        })
    } else if (str == 'in') {
      router.push({ path: 'goodsExcelImport' })
    }
  }

  // 新增物料
  const addProduct = () => {
    router.push({ path: '/commodity/add' })
  }

  // 物料详情
  const onGoToGoodDetail = (good: Good) => {
    setGoodType('spare')
    if (good.goodsType === 1) {
      setGoodType('product')
    }
    if (!good.id) return
    router.push({ path: `/commodity/commodi/detail/${good.id}` })
  }

  const handleMultipleOperate = (type: 'delete' | 'disable' | 'enable') => {
    let message = ''
    switch (type) {
      case 'delete':
        message = '删除'
        break
      case 'disable':
        message = '禁用'
        break
      case 'enable':
        message = '启用'
        break
    }
    if (selectedGoods.value.length === 0) {
      HMessageBox.error(`请选择要${message}的物料`)
      return
    }
    const productIds = selectedGoods.value
      .filter((item) => item.goodsType === 1)
      .map((item) => item.id)
    const spareIds = selectedGoods.value
      .filter((item) => item.goodsType === 2)
      .map((item) => item.id)
    ElMessageBox({
      type: type === 'delete' ? 'error' : 'warning',
      title: '提示',
      message: `确认${message}选中的物料?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: async (action: Action, instance: MessageBoxState, done: () => void) => {
        if (action === 'confirm') {
          if (type === 'delete') {
            instance.confirmButtonLoading = true
            instance.cancelButtonLoading = true
            if (productIds.length > 0) {
              const productMultipleDeleteResult = await productMultipleDelete(productIds)
              ElMessage({
                type: productMultipleDeleteResult.success ? 'success' : 'error',
                message: productMultipleDeleteResult.message,
                plain: true,
                duration: 5000,
                showClose: true,
              })
            }
            if (spareIds.length > 0) {
              const spareMultipleDeleteResult = await spareMultipleDelete(spareIds)
              ElMessage({
                type: spareMultipleDeleteResult.success ? 'success' : 'error',
                message: spareMultipleDeleteResult.message,
                plain: true,
                duration: 5000,
                showClose: true,
              })
            }
            instance.confirmButtonLoading = false
            instance.cancelButtonLoading = false
            done()
            getList()
          }

          if (type === 'disable') {
            instance.confirmButtonLoading = true
            instance.cancelButtonLoading = true
            if (productIds.length > 0) {
              const productMultipleDisableResult = await productMultipleDisable(productIds)
              ElMessage({
                type: productMultipleDisableResult.success ? 'success' : 'error',
                message: productMultipleDisableResult.message,
                plain: true,
                duration: 5000,
                showClose: true,
              })
            }
            if (spareIds.length > 0) {
              const spareMultipleDisableResult = await spareMultipleDisable(spareIds)
              ElMessage({
                type: spareMultipleDisableResult.success ? 'success' : 'error',
                message: spareMultipleDisableResult.message,
                plain: true,
                duration: 5000,
                showClose: true,
              })
            }
            instance.confirmButtonLoading = false
            instance.cancelButtonLoading = false
            done()
            getList()
          }

          if (type === 'enable') {
            instance.confirmButtonLoading = true
            instance.cancelButtonLoading = true
            if (productIds.length > 0) {
              const productMultipleEnableResult = await productMultipleEnable(productIds)
              ElMessage({
                type: productMultipleEnableResult.success ? 'success' : 'error',
                message: productMultipleEnableResult.message,
                plain: true,
                duration: 5000,
                showClose: true,
              })
            }
            if (spareIds.length > 0) {
              const spareMultipleEnableResult = await spareMultipleEnable(spareIds)
              ElMessage({
                type: spareMultipleEnableResult.success ? 'success' : 'error',
                message: spareMultipleEnableResult.message,
                plain: true,
                duration: 5000,
                showClose: true,
              })
            }
            instance.confirmButtonLoading = false
            instance.cancelButtonLoading = false
            done()
            getList()
          }
        }

        if (action === 'cancel' || action === 'close') {
          done()
        }
      },
    })
  }

  const getGoodsTypeFun = () => {
    loading.value = true
    getGoodsType().then((res) => {
      if (res.data.code === 20000) {
        goodTypeList.value[0].childData = res.data.data.rows
      }
      loading.value = false
    })
  }

  /**
   * 批量启用或禁用批号管理
   * @param {boolean} result - true-启用，false-禁用
   */
  const handleMultipleEnableOrDisableBatchNo = (result: boolean) => {
    ElMessageBox({
      title: '提示',
      message: `确定${result ? '启用' : '禁用'}选中商品的批号管理`,
      autofocus: false,
      showCancelButton: true,
      type: 'warning',
      async beforeClose(action, instance, done) {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.cancelButtonLoading = true
          const requestParam = {
            enableBatchNo: result,
            batchNoGoodsVos: selectedGoods.value.map((item) => {
              return {
                goodsId: item.id,
                type: item.goodsType,
              }
            }),
          }
          const res = await multipleEnableOrDisableBatchNo(requestParam)
          instance.confirmButtonLoading = false
          instance.cancelButtonLoading = false
          if (res.data.code === 20000) {
            HMessage.success(result ? '启用成功' : '禁用成功')
            getList()
            done()
            return
          }
          HMessageBox.error(res.data.message)
          return
        }

        done()
      },
    })
  }

  /**
   * 核心物料筛选事件
   * @param {boolean} value - 选择的值
   */
  const handleCoreMaterialFilter = (value: boolean | null) => {
    getGoodListParam.value.coreMaterials = value
    getList()
  }

  const handleEditClick = (good: GoodItem) => {
    router.push({ path: `/commodity/commodi/edit/${good.id}` })
  }

  const handleUpdateMobileVisibleClick = (visible: 0 | 1) => {
    ElMessageBox({
      title: '提示',
      message: `确定要移动端${visible === 1 ? '显示' : '隐藏'}将选中的产品？`,
      autofocus: false,
      type: 'warning',
      showCancelButton: true,
      async beforeClose(action, instance, done) {
        if (action === 'confirm') {
          try {
            instance.cancelButtonLoading = true
            instance.confirmButtonLoading = true
            const res = await setGoodListMobileVisible(
              visible,
              selectedGoods.value.map((good) => good.code),
            )
            instance.cancelButtonLoading = false
            instance.confirmButtonLoading = false
            if (res.data.code === 20000) {
              HMessage.success('修改完成')
              getList()
              done()
              return
            }
            HMessageBox.error(res.data.message)
          } catch (error) {
            instance.cancelButtonLoading = false
            instance.confirmButtonLoading = false
          }
          return
        }

        done()
      },
    })
  }

  onMounted(() => {
    getGoodsTypeFun()
    getBrandOptions()
    getUnitOptions()
    getList()
  })

  router.beforeResolve((to, from, next) => {
    if (from.name === 'detail') {
      getList()
    }
    next()
  })
</script>

<style scoped lang="scss">
  .good-list-wrapper {
    height: calc(100vh - 92px);
    box-sizing: border-box;
    padding: 12px;

    .good-list {
      background-color: #fff;
      box-sizing: border-box;
      padding: 12px;
      height: 100%;
      display: flex;
      flex-direction: column;

      .title {
        display: flex;
        align-items: center;
        column-gap: 4px;
        height: 19px;
        line-height: 19px;

        .line {
          width: 3px;
          height: 14px;
          border-radius: 0px;
          background-color: $primaryColor;
          border: 0;
        }

        .text {
          font-size: 14px;
          line-height: 15px;
        }
      }

      .line {
        border-bottom: 1px dotted $dottedLine;
        margin: 12px 0;
      }

      .body {
        flex: 1;
        height: 0;
        display: flex;
        background-color: #fff;
        overflow: hidden;

        .sidebar {
          // width: 225px;
          display: flex;
          flex-direction: column;

          .header {
            height: 28px;
            display: flex;
            align-items: center;
            justify-content: space-between;
          }

          .line {
            margin: 12px 0;
            border-bottom: 1px solid #ebeef5;
          }

          .trees_container {
            flex: 1;
            display: flex;
            flex-direction: column;
            height: 100%;
            overflow-y: auto;
            margin-right: -4px;
            padding-right: 4px;
            box-sizing: border-box;

            &::-webkit-scrollbar-track {
              background: transparent; //背景颜色
            }

            .tree_box {
              // flex: 1;
              // padding-bottom: 50px;
              box-sizing: border-box;
            }

            .tree_item {
              width: 100%;
              height: 32px;
              box-sizing: border-box;
              padding: 0 24px;
              font-size: 12px;
              line-height: 32px;
              border-radius: 1px;
              display: flex;
              justify-content: space-between;
              color: #606266;
              cursor: pointer;

              .btn_group {
                display: flex;
                column-gap: 8px;
                align-items: center;
              }

              &:hover {
                background-color: #007bff23;
              }
            }

            .active_tree_item {
              color: #fff !important;
              background-color: #007cff !important;
            }

            // :deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
            //   color: #007cff !important;
            //   background-color: #007bff23 !important;
            // }
            :deep(.el-tree) {
              --el-tree-node-hover-bg-color: #007bff23;

              .el-tree-node__content {
                height: 32px;
                border-radius: 2px;

                .custom-tree-node {
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  width: 100%;
                  box-sizing: border-box;
                  height: 100%;
                }
              }

              .el-tree-node__content:has(.is_disable) {
                cursor: not-allowed;
              }

              .el-tree-node__content:has(.is_active_tree_item) {
                color: #fff !important;
                background-color: #007cff;

                .el-tree-node__expand-icon {
                  color: #fff !important;
                }
              }
            }
          }

          .page_pages {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 10px;
            color: #606266;
          }
        }

        .line {
          margin: 0 12px;
          border-left: 1px solid #dcdfe6;
        }

        .main {
          height: 100%;
          display: flex;
          flex-direction: column;
          row-gap: 12px;
          width: calc(100% - 240px - 25px);

          .header {
            width: 100%;
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            row-gap: 12px;
            column-gap: 5px;

            .btn_group {
              display: flex;
              column-gap: 5px;
            }

            .search {
              display: flex;
              flex-wrap: wrap;
              gap: 5px;

              :deep(.el-select) {
                width: 120px;
              }

              :deep(.el-input) {
                width: 200px;
              }
            }
          }

          .table-pagination-wrapper {
            flex: 1;
            height: 0;
            display: flex;
            flex-direction: column;
            row-gap: 12px;

            .table {
              max-height: calc(100% - 40px);
              min-height: 100px;
            }

            .pagination {
              display: flex;
              align-items: center;
              column-gap: 12px;
              justify-content: flex-end;
            }
          }
        }
      }
    }
  }

  .select_header {
    display: flex;
    column-gap: 5px;
  }

  .add_type_modal_form {
    display: flex;
    justify-content: center;

    :deep(.el-form-item) {
      width: 300px;

      .el-form-item__label {
        margin: 0 0 3px 0;
        height: 16px;
        line-height: 16px;
      }
    }
  }

  .app-container {
    :deep(.el-dialog .el-dialog__body) {
      margin: 0 10px;
      margin-top: 10px;
    }
  }

  .back_bg {
    background-color: #fff !important;
    display: flex;
    flex-direction: column;
    flex: 1;
  }

  .header_top {
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    padding-left: 10px;
    border-bottom: 1px solid #e5e5e5;
  }

  .main {
    display: flex;
    flex: 1;

    :deep(.el-card.is-always-shadow) {
      box-shadow: none;
    }

    .box-card {
      position: relative;
      box-sizing: border-box;
      padding-bottom: 10px;
      padding-right: 10px;
      border-radius: 0;
      border: 0;
      padding-left: 10px;
      border-right: 1px solid #eee;

      :deep(.el-card__body) {
        padding: 0;
      }

      .header {
        padding: 10px 10px 10px 0;
        margin-bottom: 2px;
        border-bottom: 1px solid #e5e5e5;
        display: flex;
        justify-content: space-between;
        align-items: center;

        h4 {
          font-size: 12px;
        }

        span {
          color: #007cff;
          cursor: pointer;
          margin-left: 10px;
        }
      }

      .tree {
        margin-bottom: 10px;
      }

      .page_pages {
        width: 100%;
        overflow-x: auto;
        padding: 0 6px;
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        bottom: 10px;
      }
    }

    .el-main {
      --el-main-padding: 0px;
      background-color: #fff;
      height: 100%;
      display: flex;
      flex-direction: column;
    }

    .list {
      box-sizing: border-box;
      margin: 10px 10px 0 10px;
      display: flex;
      flex-direction: column;
      flex: 1;

      .header {
        display: flex;
        flex-direction: column;
        row-gap: 12px;
        padding-bottom: 12px;

        .btn_group {
          display: flex;
          column-gap: 5px;
        }

        .filter_form {
          display: flex;
          column-gap: 5px;
          flex-wrap: wrap;
          row-gap: 12px;

          :deep(.el-select) {
            min-width: 110px;
            max-width: 110px;
          }

          :deep(.el-input) {
            min-width: 228px;
            max-width: 228px;
          }
        }
      }

      .table_h {
        margin-bottom: 10px;
        position: relative;
        flex: 1;
        height: 100%;

        .color_text {
          color: #007cff;
          cursor: pointer;

          &:hover {
            text-decoration: underline;
          }
        }
      }

      .btns {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: wrap;
        width: 100%;

        .btns-right {
          display: flex;
          align-items: center;
          flex-wrap: wrap;

          :deep(.el-select .el-input__inner) {
            cursor: text;
          }

          .ml5 {
            width: calc((100vw / 100) * 7);
            min-width: 150px;
            margin-right: 5px;
            margin-bottom: 10px;
          }

          .mr5 {
            margin-right: 5px;
          }

          &:last-child {
            margin-right: 0;
          }

          .btn {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
          }
        }

        .btns-left {
          display: flex;
          align-items: center;
          margin-bottom: 10px;

          .iconfont {
            margin-right: 5px;
          }

          .btn {
            display: flex;
            align-items: center;
          }
        }
      }

      .mr5 {
        margin-right: 5px;
      }
    }

    .footer {
      padding: 0 0 10px;
      // margin-top: 10px;
      // border-top: 1px solid #e5e5e5;

      span {
        color: #b6b2b5;
      }
    }
  }

  .my-header {
    h3 {
      color: #000;
      font-size: 14px;
    }
  }

  .btn_dele {
    color: #fff;
    width: 60px;
  }

  .dialog-footer {
    .btn_dialog {
      color: #fff;
      width: 60px;
    }

    .btn_dialog_Cancel {
      width: 60px;

      &:hover {
        border: 1px solid #e5e5e5;
        color: #999;
        background-color: #e5e5e5;
      }
    }
  }

  .delete_title {
    display: flex;
    align-items: center;

    h4 {
      font-size: 14px;
      margin-left: 10px;
    }
  }

  .el-tag.el-tag--success {
    --el-tag-text-color: #00c0c0;
    --el-tag-bg-color: #ebf6f6;
    --el-tag-border-color: #ebf6f6;
    --el-tag-hover-color: #00c0c0;
  }

  .el-tag.el-tag--info {
    --el-tag-border-color: var(--el-color-info-light-9);
  }

  .el-tag {
    --el-tag-border-color: var(--el-color-primary-light-9);
  }

  .el-tag.el-tag--warning {
    --el-tag-border-color: var(--el-color-warning-light-9);
  }

  :deep(.el-dropdown) {
    height: 20px;
    font-size: 12px;
  }
</style>
